// miniprogram/pages/index/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navState: 0,  //导航状态

    // swiper 高度自适应锚点属性
    anchor: {
      deviceHeight: 0,
      anchorTop: 0,
      anchorBottom: 0,
      anchorScreenBottom: 0
    },

    addBacklogMaskTrue: false,  // 是否显示添加层

    /** UI状态变量 */
    switchColor: '',
    finishSwitchColor: '',
    cakeMarginLeft: '',
    finishCakeMarginLeft: '',
    is_remind: false,
    is_finish: false,
    MaskMethod: '',
    updateShowFinishBut: false,

    /** 请求缓存属性 */
    backlogList: [],
    scheduleList: {},

    /** 页内数据临时缓存属性 */
    backlog: {},
    datetimeStr: null,   // CURD时间显示值

    /**日期时间选择器相关属性 */
    time: null,
    dateTimeArray: null,
    dateTime: null,   // 选择器当前选择值
    startYear: 2000,
    endYear: 2050,

    userInfo: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.backlogList()
    this.scheduleList()
    this.getDateTime()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.computeSwiperHeight(0)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.isLogin()
    // console.log(this.data.backlogList)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  isLogin: function () {
    // 检查是否登录
    this.setData({
      userInfo: wx.getStorageSync('userInfo'),
      hasUserInfo: wx.getStorageSync('hasUserInfo')
    })
    if (this.data.hasUserInfo == "") {
      // this.wechatLogin()
      console.log("请点击授权！")
    } else {
      wx.setNavigationBarTitle({
        title: this.data.userInfo.nickName + '的高效生活'
      })
    }
  },

  // 页面路由
  toSwitchTab: function (event) {
    var url = event.currentTarget.dataset.pageurl
    wx.switchTab({
      url: url,
    })
  },
  toNavigateTo: function (event) {
    var url = event.currentTarget.dataset.pageurl
    wx.navigateTo({
      url: url,
    })
  },
  toRedirectTo: function (event) {
    var url = event.currentTarget.dataset.pageurl
    wx.redirectTo({
      url: url,
    })
  },

  //监听滑块
  bindchange(e) {
    // console.log(e.detail.current)
    let index = e.detail.current;
    this.setData({
      navState: index
    })
  },
  //点击导航
  navSwitch: function (e) {
    // console.log(e.currentTarget.dataset.index)
    let index = e.currentTarget.dataset.index;
    this.setData({
      navState: index
    })
  },

  // swiper 高度自适应
  computeSwiperHeight(pageIndex) {
    let getSwiperHeight = () => {
      let min = this.data.anchor.anchorScreenBottom - this.data.anchor.anchorTop;
      let value = this.data.anchor.anchorBottom - this.data.anchor.anchorTop
      return Math.max(min, value)
    }
    wx.createSelectorQuery()
      .select('.anchor-screen-bottom')
      .boundingClientRect()
      .selectViewport()
      .scrollOffset()
      .exec(res => {
        this.data.anchor.anchorScreenBottom = res[0].bottom
      })
    wx.createSelectorQuery()
      .select('.anchor-top')
      .boundingClientRect()
      .selectViewport()
      .scrollOffset()
      .exec(res => {
        this.data.anchor.anchorTop = res[0].top
        this.setData({
          'anchor.deviceHeight': getSwiperHeight()
        })
        // console.log(getSwiperHeight())
      })
    wx.createSelectorQuery()
      .select('.anchor-bottom')
      .boundingClientRect()
      .selectViewport()
      .scrollOffset()
      .exec(res => {
        this.data.anchor.anchorBottom = res[0].bottom
        this.setData({
          'anchor.deviceHeight': getSwiperHeight()
        })
      })
    // console.log(getSwiperHeight())
  },

  // 显示弹出层
  showBocklogMask: function (event) {
    
    var index = event.currentTarget.dataset.index
    // console.log(this.data.backlogList[index].datetime)
    this.setData({
      addBacklogMaskTrue: true,
      MaskMethod: event.currentTarget.dataset.method
    })
    if (this.data.navState == 0) {
      var data = this.data.backlogList[index]
      if (event.currentTarget.dataset.method == "update" && this.data.backlogList[index].is_remind == true) {
        this.remindOn()
      } else if (event.currentTarget.dataset.method == "update" && this.data.backlogList[index].is_remind == false) {
        this.remindOff()
      }
      if (event.currentTarget.dataset.method == "update") {
        let datetime = this.data.backlogList[index].datetime
        this.setData({
          is_remind: data.is_remind,
          is_reminded: data.is_reminded,
          backlog: data,
          datetimeStr: datetime,
          updateShowFinishBut: true
        })
        console.log(this.data.updateShowFinishBut)
      }
    } else if (this.data.navState == 1) {
      var data = this.data.scheduleList[index]

      if (event.currentTarget.dataset.method == "update" && this.data.scheduleList[index].is_remind == true) {
        this.remindOn()
      } else if (event.currentTarget.dataset.method == "update" && this.data.scheduleList[index].is_remind == false) {
        this.remindOff()
      }
      if (event.currentTarget.dataset.method == "update") {
        console.log(this.data.updateShowFinishBut)
        let datetime = this.data.scheduleList[index].datetime
        this.setData({
          is_remind: data.is_remind,
          backlog: data,
          time: datetime,
        })
      }
    }
    // console.log(this.data.backlog)
  },

  // 隐藏弹出层
  hideBacklogMask: function (event) {

    this.setData({
      addBacklogMaskTrue: false,
      backlog: {},
      datetimeStr: '',
      updateShowFinishBut: false
    })
  },

  // 在中间阻止事件冒泡，实现点击隐藏弹出层
  stopPropagation: function () {

  },


  // 日期时间选择器方法
  changeDateTime: function (event) {
    // console.log(event.detail.value)
    
    if(this.data.navState == 0){
      let subscript = [event.detail.value].concat()
      let datetimeStr = this.data.dateTimeArray[0][subscript[0][0]] + '-' + this.data.dateTimeArray[1][subscript[0][1]] + '-' + this.data.dateTimeArray[2][subscript[0][2]] + ' ' + this.data.dateTimeArray[3][subscript[0][3]] + ':' + this.data.dateTimeArray[4][subscript[0][4]]
      
      this.setData({
        dateTime: event.detail.value,
        datetimeStr: datetimeStr
      });
    }else if(this.data.navState == 1){
      this.setData({
        time: event.detail.value,
      });
    }
  },
  changeDateTimeColumn: function (e) {
    var arr = this.data.dateTime, dateArr = this.data.dateTimeArray;
    arr[e.detail.column] = e.detail.value;
    dateArr[2] = this.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);

    this.setData({
      dateTimeArray: dateArr,
      dateTime: arr
    });
  },
  getDateTime: function () {
    // 获取完整的年月日 时分秒，以及默认显示的数组
    var obj = this.dateTimePicker(this.data.startYear, this.data.endYear);
    var obj1 = this.dateTimePicker(this.data.startYear, this.data.endYear);
    // 精确到分的处理，将obj1数组的秒去掉
    var lastArray = obj1.dateTimeArray.pop();
    var lastTime = obj1.dateTime.pop();

    this.setData({
      dateTime: obj1.dateTime,
      dateTimeArray: obj1.dateTimeArray,
    });
    // console.log(obj.dateTime)
    // console.log(obj1.dateTime)
    // console.log(obj1.dateTimeArray)
  },


  // 获取年月日工具方法
  GMTToStr: function (time) {
    let date = new Date(time)
    let Str = date.getFullYear() + '-' +
      (date.getMonth() + 1) + '-' +
      date.getDate() + ' ' +
      date.getHours() + ':' +
      date.getMinutes()
    return Str
  },
  withData: function (param) {
    return param < 10 ? '0' + param : '' + param;
  },
  getLoopArray: function (start, end) {
    var start = start || 0;
    var end = end || 1;
    var array = [];
    for (var i = start; i <= end; i++) {
      array.push(this.withData(i));
    }
    // console.log(array)
    return array;
  },
  getMonthDay: function (year, month) {
    var flag = year % 400 == 0 || (year % 4 == 0 && year % 100 != 0), array = null;

    switch (month) {
      case '01':
      case '03':
      case '05':
      case '07':
      case '08':
      case '10':
      case '12':
        array = this.getLoopArray(1, 31)
        break;
      case '04':
      case '06':
      case '09':
      case '11':
        array = this.getLoopArray(1, 30)
        break;
      case '02':
        array = flag ? getLoopArray(1, 29) : getLoopArray(1, 28)
        break;
      default:
        array = '月份格式不正确，请重新输入！'
    }
    // console.log(array)
    return array;
  },
  getNewDateArry: function () {
    // 当前时间的处理
    var newDate = new Date();
    var year = this.withData(newDate.getFullYear()),
      mont = this.withData(newDate.getMonth() + 1),
      date = this.withData(newDate.getDate()),
      hour = this.withData(newDate.getHours()),
      minu = this.withData(newDate.getMinutes()),
      seco = this.withData(newDate.getSeconds());

    return [year, mont, date, hour, minu, seco];
  },
  dateTimePicker: function (startYear, endYear, date) {
    // 返回默认显示的数组和联动数组的声明
    var dateTime = [], dateTimeArray = [[], [], [], [], [], []];
    var start = startYear || 1978;
    var end = endYear || 2100;
    // 默认开始显示数据
    var defaultDate = date ? [...date.split(' ')[0].split('-'), ...date.split(' ')[1].split(':')] : this.getNewDateArry();
    // 处理联动列表数据
    /*年月日 时分秒*/
    dateTimeArray[0] = this.getLoopArray(start, end);
    dateTimeArray[1] = this.getLoopArray(1, 12);
    dateTimeArray[2] = this.getMonthDay(defaultDate[0], defaultDate[1]);
    dateTimeArray[3] = this.getLoopArray(0, 23);
    dateTimeArray[4] = this.getLoopArray(0, 59);
    dateTimeArray[5] = this.getLoopArray(0, 59);

    dateTimeArray.forEach((current, index) => {
      dateTime.push(current.indexOf(defaultDate[index]));
      // dateTime.push(defaultDate[index]);
    });
    //  console.log(dateTimeArray)
    return {
      dateTimeArray: dateTimeArray,
      dateTime: dateTime
    }
  },

  // 设置任务提醒通知
  // 开启状态
  remindOn: function () {
    this.setData({
      is_remind: true
    })
    var query = wx.createSelectorQuery()
    query.select('cake').boundingClientRect()
    query.exec(res => {
      let px = 6
      while (px < 32) {
        this.setData({
          cakeMarginLeft: px
        })
        px++
      }
      this.setData({
        switchColor: 'rgb(19, 169, 234)'
      })
    })
  },
  // 关闭状态
  remindOff: function () {
    this.setData({
      is_remind: false
    })
    var query = wx.createSelectorQuery()
    query.select('cake').boundingClientRect()
    query.exec(res => {
      let px = 31
      while (px > 6) {
        this.setData({
          cakeMarginLeft: px
        })
        px--
      }
      this.setData({
        switchColor: 'rgba(128, 128, 128, .3)'
      })
    })
  },
  onRemind: function (event) {
    var is_remind = this.data.is_remind

    // 点击按钮动画
    if (is_remind == false) {
      this.remindOn()
    } else {
      this.remindOff()
    }
    wx.showModal({
      title: '提示',
      content: '提醒功能需占用较多系统资源，运营资金有限，暂时关闭！',
      success(res) {
        if (res.confirm) {
          wx.switchTab({
            url: '../index/index',
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
    // console.log(this.data.is_remind)
  },

// 结束任务按钮
  // 开启状态
  finishOn: function () {
    this.setData({
      is_finish: true
    })
    var query = wx.createSelectorQuery()
    query.select('cake').boundingClientRect()
    query.exec(res => {
      let px = 6
      while (px < 32) {
        this.setData({
          finishCakeMarginLeft: px
        })
        px++
      }
      this.setData({
        finishSwitchColor: 'rgb(19, 169, 234)'
      })
    })
  },
  // 关闭状态
  finishOff: function () {
    this.setData({
      is_finish: false
    })
    var query = wx.createSelectorQuery()
    query.select('cake').boundingClientRect()
    query.exec(res => {
      let px = 31
      while (px > 6) {
        this.setData({
          finishCakeMarginLeft: px
        })
        px--
      }
      this.setData({
        finishSwitchColor: 'rgba(128, 128, 128, .3)'
      })
    })
  },

  onFinish: function (event) {
    var is_finish = this.data.is_finish

    // 点击按钮动画
    if (is_finish == false) {
      this.finishOn()
    } else {
      this.finishOff()
    }
  },

  // 添加待办事项
  backlogAddOrUpdate: function (event) {
    // console.log(event.detail.value)

    if (this.data.MaskMethod == 'add') {
      let datetime = null;
      if(this.data.navState == 0){
        datetime = this.data.datetimeStr
      }else if(this.data.navState == 1){
        datetime = this.data.time
      }

      // add
      wx.cloud.callFunction({
        // 要调用的云函数名称
        name: 'backlogAdd',
        // 传递给云函数的event参数
        // class属性，0表示待办事项，1表示日程表
        data: {
          class: this.data.navState,
          datetime: datetime,
          content: event.detail.value.content,
          is_remind: this.data.is_remind,
        }
      }).then(res => {
        // console.log(res)
        this.hideBacklogMask()
        this.onLoad()
      }).catch(err => {
        // handle error
        console.log(err)
      })
    } else if (this.data.MaskMethod == 'update') {
      // update
      let datetime = null;
      if(this.data.navState == 0){
        datetime = this.data.datetimeStr
      }else if(this.data.navState == 1){
        datetime = this.data.time
      }
      console.log(this.data.is_reminded)
      wx.cloud.callFunction({
        // 要调用的云函数名称
        name: 'backlogUpdate',
        // 传递给云函数的event参数
        data: {
          class: this.data.navState,
          _id: this.data.backlog._id,
          datetime: datetime,
          content: event.detail.value.content,
          is_remind: this.data.is_remind,
          is_reminded: this.data.is_finish,
        }
      }).then(res => {
        // console.log(res)
        this.hideBacklogMask()
        this.onLoad()
      }).catch(err => {
        // handle error
        console.log(err)
      })
    }
  },

  // 加载待办事项列表
  backlogList: function () {
    wx.cloud.callFunction({
      // 要调用的云函数名称
      name: 'backlogList',
      data: {
        class: 0
      }
    }).then(res => {
      // console.log(res)
      this.setData({
        backlogList: res.result.data
      })

      // console.log(this.data.backlogList)
    }).catch(err => {
      // handle error
      console.log(err)
    })
  },
  // 加载每日日程列表
  scheduleList: function () {
    wx.cloud.callFunction({
      // 要调用的云函数名称
      name: 'backlogList',
      data: {
        class: 1
      }
    }).then(res => {
      // console.log(res)
      this.setData({
        scheduleList: res.result.data
      })
    }).catch(err => {
      // handle error
      console.log(err)
    })
  },

  // 长按删除待办事项
  longpressRemove: function (event) {
    var id = event.currentTarget.dataset._id
    var self = this
    wx.showModal({
      title: '删除',
      content: event.currentTarget.dataset.content,
      success(res) {
        if (res.confirm) {
          // console.log('用户点击确定')
          wx.cloud.callFunction({
            // 要调用的云函数名称
            name: 'backlogRemove',
            // 传递给云函数的event参数
            data: {
              class: self.data.navState,
              _id: id,
            }
          }).then(res => {
            // console.log(res)
            self.onLoad()
          }).catch(err => {
            console.log(err)
          })
        } else if (res.cancel) {
          // console.log('用户点击取消')
        }
      }
    })
  },
  // 请求订阅消息推送授权
  requestMessageAuth: function () {
    let templateId = '5E2kzq-gqu8UE6bB89slTl8YEBp_qz6ou8vGCQt0xUk'
    wx.requestSubscribeMessage({
      tmplIds: [templateId],
      success(res) {
        // console.log(res)
        console.log("授权成功！")
      }
    })
  },

  test: function (event) {
    wx.cloud.callFunction({
      // 要调用的云函数名称
      name: 'timingRemind',
    }).then(res => {
      console.log(res)
    }).catch(err => {
      // handle error
      console.log(err)
    })
    // console.log(event)
  }
})